importScripts('utils.js');

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  switch (message?.action) {
    case 'bindCard':
      handleBindCard(message.data).catch((error) => {
        console.error('一键绑卡流程触发失败:', error);
      });
      sendResponse({ success: true, message: '已开始一键绑卡流程' });
      return true;
    case 'registerAccount':
      handleRegisterAccount(message.data)
        .then(() => sendResponse({ success: true, message: '注册信息已尝试提交' }))
        .catch((error) => {
          console.error('一键注册触发失败:', error);
          sendResponse({ success: false, message: error.message });
        });
      return true;
    case 'fillVerificationCode':
      handleFillVerificationCode(message.data)
        .then(() => sendResponse({ success: true }))
        .catch((error) => {
          console.error('填写验证码失败:', error);
          sendResponse({ success: false, message: error.message });
        });
      return true;
    default:
      sendResponse({ success: false, message: '未知的操作' });
      return false;
  }
});

const PageType = {
  AUGMENT_BIND: 'augment_bind',
  AUGMENT_OTHER: 'augment_other',
  CURSOR_BIND: 'cursor_bind',
  CURSOR_OTHER: 'cursor_other',
  UNKNOWN: 'unknown',
};

async function detectPageType(tabId) {
  try {
    const tab = await chrome.tabs.get(tabId);
    const tabUrl = (tab.url || '').toLowerCase();
    const [{ result } = {}] = await chrome.scripting.executeScript({
      target: { tabId },
      func: () => ({
        title: document.title,
        href: window.location.href,
        hostname: window.location.hostname,
      }),
    });

    if (!result) {
      console.warn('⚠️ 无法获取页面信息');
      return PageType.UNKNOWN;
    }

    const { title, hostname, href } = result;
    const normalizedTitle = (title || '').toLowerCase();
    const normalizedHost = (hostname || '').toLowerCase();

    const isAugmentBilling = normalizedHost === 'billing.augmentcode.com';
    const isAugmentOther = normalizedHost.includes('augmentcode.com') && !isAugmentBilling;
    const isStripeCheckout = normalizedHost === 'checkout.stripe.com';
    const isCursor = normalizedHost.includes('cursor.com');
    const looksLikeAugmentPage = normalizedTitle.includes('augment code');
    const looksLikeCursorPage = normalizedTitle.includes('cursor');

    if (isAugmentBilling && looksLikeAugmentPage) {
      console.log(`✅ 检测到 Augment 绑卡页面 - URL: ${href}, Title: ${title}`);
      return PageType.AUGMENT_BIND;
    }

    if (isAugmentOther) {
      console.log(`✅ 检测到 Augment 其他页面 - URL: ${href}, Title: ${title}`);
      return PageType.AUGMENT_OTHER;
    }

    if (isStripeCheckout && looksLikeCursorPage) {
      console.log(`✅ 检测到 Cursor 绑卡页面 - URL: ${href}, Title: ${title}`);
      return PageType.CURSOR_BIND;
    }

    if (isCursor) {
      console.log(`✅ 检测到 Cursor 其他页面 - URL: ${href}, Title: ${title}`);
      return PageType.CURSOR_OTHER;
    }

    console.log(`❌ 未识别的页面类型 - URL: ${tabUrl}, Title: ${title}`);
    return PageType.UNKNOWN;
  } catch (error) {
    console.error('❌ 页面类型检测失败:', error);
    return PageType.UNKNOWN;
  }
}

async function performCardFilling(tabId, cardData) {
  console.log('🔄 开始银行卡填充流程');
  const pageType = await detectPageType(tabId);

  switch (pageType) {
    case PageType.CURSOR_BIND:
      console.log('✅ 检测到 Cursor 绑卡页面');
      await chrome.scripting.executeScript({
        target: { tabId },
        func: selectCardPaymentMethod,
      });
      await sleep(1000);
      break;
    case PageType.AUGMENT_BIND:
      console.log('✅ 检测到 Augment 绑卡页面，跳过选择支付方式步骤');
      break;
    case PageType.AUGMENT_OTHER:
    case PageType.CURSOR_OTHER:
    case PageType.UNKNOWN:
      console.log('⚠️ 页面类型不明确，尝试执行标准流程');
      await chrome.scripting.executeScript({
        target: { tabId },
        func: selectCardPaymentMethod,
      });
      await sleep(1000);
      break;
    default:
      break;
  }

  await chrome.scripting.executeScript({
    target: { tabId },
    func: executeCardFillProcess,
    args: [cardData],
  });

  console.log('✅ 银行卡填充流程完成！');
}

async function handleBindCard(cardData) {
  try {
    const [activeTab] = await chrome.tabs.query({ active: true, currentWindow: true });

    if (!activeTab?.id) {
      console.error('无法获取当前标签页');
      return;
    }

    const tabId = activeTab.id;
    console.log('🚀 开始一键绑卡流程');

    const [{ result: alreadyOnBindPage } = {}] = await chrome.scripting.executeScript({
      target: { tabId },
      func: checkBindPageReady,
    });

    if (alreadyOnBindPage) {
      console.log('✅ 检测到当前已在支付页面，直接执行填充');
      await performCardFilling(tabId, cardData);
      return;
    }

    const clickedPaymentButton = await attemptClickAddPaymentButton(tabId);
    if (clickedPaymentButton) {
      await chrome.storage.local.set({ pendingCardData: cardData });
      console.log('🖱️ 检测到 Add Payment Method 按钮，已点击并等待跳转...');
      setupBindCardPageListener(tabId);
      return;
    }

    const url = new URL(activeTab.url);
    const hostname = url.hostname.replace(/^www\./, '');

    if (!hostname.includes('cursor.com')) {
      console.error(`当前域名 ${hostname} 不是 cursor.com`);
      return;
    }

    await chrome.storage.local.set({ pendingCardData: cardData });
    console.log('📋 调用 getCheckoutUrl 获取绑卡页面 URL...');

    try {
      await chrome.scripting.executeScript({
        target: { tabId },
        files: ['utils.js'],
      });

      const [{ result } = {}] = await chrome.scripting.executeScript({
        target: { tabId },
        func: async () => {
          if (typeof getCheckoutUrl === 'function') {
            return getCheckoutUrl('pro');
          }
          console.error('getCheckoutUrl 函数未找到');
          return { success: false, error: 'Function not found' };
        },
      });

      if (result?.success) {
        console.log(`✅ 成功获取绑卡页面 URL: ${result.url}`);
        await chrome.tabs.update(tabId, { url: result.url });
        setupBindCardPageListener(tabId);
      } else {
        const errorMessage = result?.error ?? 'Unknown error';
        console.error(`❌ 获取绑卡页面 URL 失败: ${errorMessage}`);
      }
    } catch (error) {
      console.error('❌ 执行 getCheckoutUrl 失败:', error);
    }
  } catch (error) {
    console.error('一键绑卡失败:', error);
  }
}

async function handleRegisterAccount(payload) {
  const email = payload?.email;
  if (!email) {
    throw new Error('缺少邮箱地址');
  }
  let targetTabId = payload?.tabId;
  if (!targetTabId) {
    const [activeTab] = await chrome.tabs.query({ active: true, currentWindow: true });
    if (!activeTab?.id) {
      throw new Error('无法获取当前标签页');
    }
    targetTabId = activeTab.id;
  }
  const [{ result } = {}] = await chrome.scripting.executeScript({
    target: { tabId: targetTabId },
    func: fillRegistrationForm,
    args: [{ email }],
  });
  if (!result?.filled) {
    throw new Error('未能填写用户名输入框');
  }
  return result;
}

async function handleFillVerificationCode(payload) {
  const code = payload?.code;
  if (!code) {
    throw new Error('缺少验证码');
  }
  let targetTabId = payload?.tabId;
  if (!targetTabId) {
    const [activeTab] = await chrome.tabs.query({ active: true, currentWindow: true });
    if (!activeTab?.id) {
      throw new Error('无法获取当前标签页');
    }
    targetTabId = activeTab.id;
  }
  const [{ result } = {}] = await chrome.scripting.executeScript({
    target: { tabId: targetTabId },
    func: fillVerificationCodeInput,
    args: [{ code }],
  });
  if (!result?.filled) {
    throw new Error('未能填入验证码');
  }
}

function setupBindCardPageListener(targetTabId) {
  let isChecking = false;
  let hasCompleted = false;

  const handleTabUpdated = async (tabId, changeInfo) => {
    if (tabId !== targetTabId || changeInfo.status !== 'complete') {
      return;
    }

    if (hasCompleted || isChecking) {
      if (isChecking) {
        console.log('⚠️ 跳过重复的 complete 事件');
      }
      return;
    }

    isChecking = true;

    try {
      const maxAttempts = 20;
      const interval = 500;
      let ready = false;

      for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
        await sleep(interval);
        const [{ result: isReady } = {}] = await chrome.scripting.executeScript({
          target: { tabId },
          func: checkBindPageReady,
        });

        if (isReady) {
          ready = true;
          hasCompleted = true;
          chrome.tabs.onUpdated.removeListener(handleTabUpdated);

          const storage = await chrome.storage.local.get(['pendingCardData']);
          const pendingCardData = storage.pendingCardData;

          if (pendingCardData) {
            await performCardFilling(tabId, pendingCardData);
            await chrome.storage.local.remove(['pendingCardData']);
          } else {
            console.error('❌ 未找到待填充的卡片数据');
          }
          break;
        }
      }

      if (!ready) {
        isChecking = false;
      }
    } catch (error) {
      console.error('检查绑卡页面失败:', error);
      isChecking = false;
    }
  };

  chrome.tabs.onUpdated.addListener(handleTabUpdated);

  setTimeout(() => {
    chrome.tabs.onUpdated.removeListener(handleTabUpdated);
    console.log('⏱️ 绑卡页面监听器已超时移除');
  }, 60000);
}

function executeCardFillProcess(cardData) {
  const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

  async function monitorSubmitButton(button) {
    let finished = false;
    let detectedSpinner = false;

    const interval = setInterval(() => {
      if (finished) {
        clearInterval(interval);
        return;
      }

      button.click();
      const processingLabel = document.querySelector('span[data-testid=submit-button-processing-label]');
      if (processingLabel?.getAttribute('aria-hidden') === 'false') {
        clearInterval(interval);
        detectedSpinner = true;
        finished = true;
      }
    }, 500);

    setTimeout(() => {
      if (!detectedSpinner) {
        finished = true;
        clearInterval(interval);
      }
    }, 8000);
  }

  (async () => {
    try {
      await fillPaymentForm(cardData);
    } catch (error) {
      console.error('银行卡填充失败:', error);
    }
  })();

  function showToast(message) {
    const toast = document.createElement('div');
    toast.style.cssText = `
      position: fixed;
      top: 20px;
      right: 20px;
      background: #4CAF50;
      color: white;
      padding: 12px 20px;
      border-radius: 8px;
      z-index: 999999;
      font-family: Arial, sans-serif;
      font-size: 14px;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
    `;
    toast.textContent = message;
    document.body.appendChild(toast);
    setTimeout(() => toast.remove(), 3000);
  }

  async function fillPaymentForm(fields) {
    const selectors = {
      cardNumber: ['input[name=cardNumber]'],
      expiryDate: ['input[name="cardExpiry"]'],
      cvc: ['input[name="cardCvc"]'],
      fullName: ['input[name="billingName"]'],
      country: ['select[name="billingCountry"]'],
      province: ['select[name="billingAdministrativeArea"]'],
      city: ['input[name="billingLocality"]'],
      address: ['input[name="billingAddressLine1"]'],
      addressLine2: ['input[name="billingAddressLine2"]'],
      postalCode: ['input[name="billingPostalCode"]'],
    };

    function fillInput(selectorList, value) {
      if (!value) {
        return false;
      }

      const normalizedValue =
        typeof value === 'string' ? value.toLowerCase() : String(value).toLowerCase();
      const upperValue =
        typeof value === 'string' ? value.toUpperCase() : String(value).toUpperCase();

      for (const selector of selectorList) {
        const elements = document.querySelectorAll(selector);
        for (const element of elements) {
          if (!element) {
            continue;
          }

          if (element.tagName.toLowerCase() === 'select') {
            const exactMatch = element.querySelector(`option[value="${value}"]`);
            if (exactMatch) {
              element.value = value;
              element.dispatchEvent(new Event('change', { bubbles: true }));
              return true;
            }

            const options = element.querySelectorAll('option');
            for (const option of options) {
              const label = option.textContent.toLowerCase();
              const optionValue = option.value.toLowerCase();

              if (
                (upperValue === 'US' &&
                  (optionValue === 'us' ||
                    optionValue === 'usa' ||
                    label.includes('united states') ||
                    label.includes('america') ||
                    label.includes('美国')))
              ) {
                element.value = option.value;
                element.dispatchEvent(new Event('change', { bubbles: true }));
                return true;
              }

              if (label.includes(normalizedValue) || optionValue.includes(normalizedValue)) {
                element.value = option.value;
                element.dispatchEvent(new Event('change', { bubbles: true }));
                return true;
              }
            }
          } else {
            element.value = value;
            ['input', 'change', 'blur', 'keyup'].forEach((eventName) => {
              element.dispatchEvent(new Event(eventName, { bubbles: true }));
            });

            if (element._valueTracker) {
              element._valueTracker.setValue('');
            }
            return true;
          }
        }
      }

      return false;
    }

    const orderedFields = [
      'cardNumber',
      'expiryDate',
      'cvc',
      'fullName',
      'country',
      'province',
      'city',
      'postalCode',
      'address',
      'addressLine2',
    ];

    let successfulCount = 0;

    async function fillNextField(index) {
      if (index >= orderedFields.length) {
        console.log(`✅ 成功填入: ${successfulCount} 个字段`);
        await delay(500);

        if (successfulCount >= 8) {
          const submitButton = document.querySelector('button[data-testid=hosted-payment-submit-button]');
          if (submitButton) {
            monitorSubmitButton(submitButton);
          }
        }

        showToast(`💳 已填入 ${successfulCount} 个字段`);
        return;
      }

      const fieldName = orderedFields[index];
      let value = fields[fieldName];

      if (fieldName === 'cardNumber' && typeof value === 'string') {
        value = value.replace(/\s/g, '');
      }

      if (value && selectors[fieldName]) {
        const filled = fillInput(selectors[fieldName], value);
        if (filled) {
          successfulCount += 1;
        }
      }

      await delay(100);
      await fillNextField(index + 1);
    }

    await delay(100);
    await fillNextField(0);
  }
}

async function selectCardPaymentMethod() {
  const delay = async (ms) => {
    const end = Date.now() + ms;
    while (Date.now() < end) {
      await new Promise((resolve) => setTimeout(resolve, Math.min(100, end - Date.now())));
    }
  };

  await delay(300);

  let toggleButton = null;
  let attempts = 0;
  const maxAttempts = 30;

  while (attempts < maxAttempts && !toggleButton) {
    attempts += 1;
    const candidate = document.querySelector('button[data-testid=card-accordion-item-button]');
    if (candidate) {
      toggleButton = candidate;
      toggleButton.click();
      break;
    }
    await delay(500);
  }

  if (!toggleButton) {
    console.error('未找到银行卡支付方式按钮');
    return;
  }

  await delay(500);

  const hostedSwitch = document.querySelector('.HostedSwitch');
  if (hostedSwitch && hostedSwitch.getAttribute('aria-checked') !== 'true') {
    hostedSwitch.click();
  }

  await delay(300);

  const manualAddressButton = document.querySelector('.AddressAutocomplete-manual-entry .Button');
  if (manualAddressButton) {
    manualAddressButton.click();
  }
}

function checkBindPageReady() {
  const cardAccordion = document.querySelector('button[data-testid=card-accordion-item-button]');
  const cardNumberInput = document.querySelector('input[name=cardNumber]');
  return Boolean(cardAccordion || cardNumberInput);
}

function fillRegistrationForm(data) {
  const email = data?.email;
  if (!email) {
    return { filled: false, clicked: false, reason: 'missing email' };
  }
  const usernameInput = document.querySelector('#username');
  if (usernameInput) {
    usernameInput.value = email;
    ['input', 'change', 'blur', 'keyup'].forEach((eventName) => {
      usernameInput.dispatchEvent(
        new Event(eventName, {
          bubbles: true,
        }),
      );
    });
  }
  const submitButton =
    document.querySelector('button[type="submit"]') || document.querySelector('input[type="submit"]');
  if (submitButton) {
    submitButton.click();
  }
  return { filled: Boolean(usernameInput), clicked: Boolean(submitButton) };
}

function fillVerificationCodeInput(data) {
  const code = data?.code;
  if (!code) {
    return { filled: false, clicked: false };
  }
  const codeInput = document.querySelector('#code');
  if (codeInput) {
    codeInput.value = code;
    ['input', 'change', 'blur', 'keyup'].forEach((eventName) => {
      codeInput.dispatchEvent(
        new Event(eventName, {
          bubbles: true,
        }),
      );
    });
  }
  const submitButton =
    document.querySelector('button[type="submit"]') || document.querySelector('input[type="submit"]');
  if (submitButton) {
    submitButton.click();
  }
  return { filled: Boolean(codeInput), clicked: Boolean(submitButton) };
}

async function attemptClickAddPaymentButton(tabId) {
  try {
    const [{ result } = {}] = await chrome.scripting.executeScript({
      target: { tabId },
      func: () => {
        const byClass = document.querySelector('button.payment-button');
        if (byClass) {
          byClass.click();
          return true;
        }

        const match = Array.from(document.querySelectorAll('button')).find((button) => {
          const text = button.textContent?.trim().toLowerCase();
          return text === 'add payment method';
        });

        if (match) {
          match.click();
          return true;
        }

        return false;
      },
    });

    return Boolean(result);
  } catch (error) {
    console.error('Add Payment Method 按钮检测失败:', error);
    return false;
  }
}
